<?php
namespace app\shouyin\admin;
use app\system\admin\Admin;
use app\system\model\systemUser as systemUserModel;
use app\user\model\User as UserModel;
use app\product\model\Product as ProductModel;
use app\shouyin\model\Deposit as DepositModel;
use app\warehouse\model\Stock as StockModel;
use app\warehouse\model\Warehouse as WarehouseModel;
use app\finance\model\Account as AccountModel;
use think\Db;
class Deposit extends Admin
{
    protected $hisiModel = 'Deposit';//模型名称[通用添加、修改专用]
    protected $hisiTable = '';//表名称[通用添加、修改专用]
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名
    protected function initialize()
    {
        parent::initialize();
        $admin = systemUserModel::get(ADMIN_ID);

        $this->assign('admin_type',$admin['type']);
        $users = UserModel::getSelect(UserModel::all());
        $this->assign('users', $users);
        if ($this->request->action() != 'index' && !$this->request->isPost()) {
            $where = [];

            $where['shop_id'] = session('shop_id');

            // 会员
            // 负责人
            $admins = systemUserModel::where($where)->all();
            $this->assign('admins', systemUserModel::getSelect($admins));
            $advisers = [];
            $technician = [];
            $cashiers = [];
            foreach ($admins as $key => $value) {
                if($value['type'] == '顾问'){
                    $advisers[] = $value;
                }else if($value['type'] == '美容师'){
                    $technician[] = $value;
                }else if($value['type'] == '前台'){
                    $cashiers[] = $value;
                }
            }
            $this->assign('cashiers', $cashiers);
            $this->assign('adviserArr', $advisers);
            $this->assign('technicians', systemUserModel::where('type', 7)->where('shop_id',session('shop_id'))->field('id as value,nick as name')->all());
            // 产品
            $products = ProductModel::all();
            $this->assign('products', ProductModel::getSelect($products));
            $WarehouseModel = new WarehouseModel;
            $warehouses = $WarehouseModel->field('id,name')->select();
		    $this->assign('warehouses',$WarehouseModel->getSelect($warehouses));

        }
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            $where      = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 15);
            $user_id    = $this->request->param('user_id', '');
            $status    = $this->request->param('status', '');
            $start    = $this->request->param('start', '2000-01-01');
            $end    = $this->request->param('end', date('Y-m-d H:i:s',time()));
            if(!empty($user_id)){
                $where['user_id'] = $user_id;
            }
            if(!empty($status)){
                $where['status'] = $status;
            }
            if(empty($start)){
                $start = '2000-01-01';
            }
            if(empty($end)){
                $end = date('Y-m-d H:i:s',time());
            }
            // halt($end);
            if(!is_empty($this->request->param('type')) && $this->request->param('type') == 2){
                $data['data'] = DepositModel::where($where)
                                ->whereTime('createtime', [strtotime($start), strtotime($end ."+1 day")])
                                ->field('*,user_id as user_name, product_id as product_name, admin_id as admin_name')
                                ->order('id desc')
                                ->select();

                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['warehouse'] = Db::name('warehouse')->where('id',$value['warehouse_id'])->value('name');
                    $data['data'][$key]['take_num'] = Db::name('deposit_log')->where('d_id',$value['id'])->sum('product_num_l');
                    $data['data'][$key]['price1']  = round($value['price'] / $value['num'], 2);
                    if($value['status'] == 1){
                        $status = '寄存';
                    }else if($value['status'] == 2){
                        $status = '领取';
                    }else if($value['status'] == 3){
                        $status = '部分领取';
                    }
                    $data['data'][$key]['status']  = $status;
                }
                $data['count'] = DepositModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end ."+1 day")])->count('id');
                $data['code'] = 0;
                return json($data);
            }else{
                $data['data'] = DepositModel::where($where)
                                ->whereTime('createtime', [strtotime($start), strtotime($end ."+1 day")])
                                ->field('*,user_id as user_name, product_id as product_name, admin_id as admin_name')
                                ->page($page)
                                ->limit($limit)
                                ->order('id desc')
                                ->select();

                foreach ($data['data'] as $key => $value) {
                    $data['data'][$key]['warehouse'] = Db::name('warehouse')->where('id',$value['warehouse_id'])->value('name');
                    if($value['num'] == 0){
                        $data['data'][$key]['price1'] = 0;
                    }else{
                        $data['data'][$key]['price1']  = round($value['price'] / $value['num'], 2);
                    }

                }
                $data['count'] = DepositModel::where($where)->where('createtime','between',[strtotime($start),strtotime($end ."+1 day")])->count('id');
                $data['code'] = 0;
                return json($data);
            }

        }
        return $this->fetch();
    }
   /**
     * [通用方法]添加页面展示和保存
     * @author 橘子俊 <364666827@qq.com>
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $postData = $this->request->post();

            if ($this->hisiValidate) {// 数据验证

                if (strpos($this->hisiValidate, '\\') === false ) {

                    if (defined('IS_PLUGINS')) {
                        $this->hisiValidate = 'plugins\\'.$this->request->param('_p').'\\validate\\'.$this->hisiValidate;
                    } else {
                        $this->hisiValidate = 'app\\'.$this->request->module().'\\validate\\'.$this->hisiValidate;
                    }

                }

                if ($this->hisiAddScene) {
                    $this->hisiValidate = $this->hisiValidate.'.'.$this->hisiAddScene;
                }

                $result = $this->validate($postData, $this->hisiValidate);
                if ($result !== true) {
                    return $this->error($result);
                }

            }



            $model = $this->model();
            $StockModel = new StockModel;
            $product_price = $StockModel->getProductPrice($postData['warehouse_id'],$postData['product_id']); // 成本价
            $warehouseModel = new WarehouseModel;
            $product_info = ProductModel::get($postData['product_id']);
            if($product_price == 0){
                $warehouse_type = $warehouseModel->warehouseType($postData['warehouse_id']);
                if($warehouse_type == 1){  //  配料库
                    $product_price = $product_info->price1 / $product_info->specs;
                }else{   //  总库
                    $product_price = $product_info->price1;
                }
            }
            $postData['unit_price'] =  $product_price * $postData['num'];
            if (!$model->save($postData)) {
                return $this->error($model->getError());
            }


            return $this->success('保存成功', '');
        }

        $template = $this->request->param('template', 'form');

        return $this->fetch($template);
    }
    public function take()
    {
        $id = $this->request->param('id');
        $formData = Db::name('deposit')->where('id', $id)->find();


        $formData['specs'] = Db::name('product')->where('id',$formData['product_id'])->value('specs');

        $formData['num_l'] = Db::name('deposit_log')->where('d_id',$formData['id'])->sum('product_num_l');

        $formData['num_s'] = $formData['num'] - $formData['num_l'];

        if($this->request->isPost()){
            // halt($formData);

            $postData        = $this->request->post();
            if(strpos($postData['product_num_l'],'.')){
                $postData['product_num_l'] = (float)$postData['product_num_l'];
            }

            if (empty($postData['id'])) {
                return $this->axiosMsg('缺少id参数',false);
            }
            if($postData['product_num_l'] == 0){
                return $this->axiosMsg('领取数量不能为0',false);
            }
            if($postData['product_num_l'] > $formData['num_s']){
                return $this->axiosMsg('领取数量超过剩余数量',false);
            }
            if(!isset($postData['ware_id']) || empty($postData['ware_id'])){
                return $this->axiosMsg('出库仓库为必填项',false);
            }
            if($formData['num_s'] - $postData['product_num_l'] == 0){
                $status = 2;
            }else{
                $status = 3;
            }
            // $warehouse_id = Db::name('warehouse')->where('shop_id',$formData['shop_id'])->where('type',1)->value('id');
            Db::startTrans();
            try {
                $price = $formData['price'];//总价格
                $unit_price = $formData['unit_price']; // 成本价
                if(is_float($postData['product_num_l'])){
                    $stock_num = $postData['product_num_l'] * $formData['specs'];
                }else{
                    $stock_num = $postData['product_num_l'];
                }
                // halt($stock_num);
                $StockModel = new StockModel;
                $begin_num = $StockModel->getBeginNum($postData['ware_id'],$postData['product_id']);
                // $warehouse_id =
                $stockDuctArr = [];
                $stockDuctArr['sn'] = $formData['sn'];
                $stockDuctArr['product_id'] = $postData['product_id'];
                $stockDuctArr['product_num'] = $stock_num;
                $stockDuctArr['product_name'] = $postData['product_name'];
                $stockDuctArr['shop_id'] = $formData['shop_id'];
                $stockDuctArr['type'] = '出库';
                $stockDuctArr['bak'] = '寄存单产品出库';
                $stockDuctArr['detailed_type'] = 2;
                $stockDuctArr['user_id'] = $formData['user_id'];
                $stockDuctArr['warehouse_id'] = $postData['ware_id'];
                $stockDuctArr['createtime'] = time();
                $stockDuctArr['status'] = 1;
                $stockDuctArr['price'] = $price / $formData['num'] * $postData['product_num_l'];
                $stockDuctArr['unit_price'] = $unit_price / $formData['num'] * $postData['product_num_l'];
                $stockDuctArr['begin_num']     = $begin_num;
                $stockDuctArr['end_num']       = $begin_num - $stock_num;
                // halt($stockDuctArr);
                Db::name('stock')->insert($stockDuctArr);

                $postData['d_id']  = $postData['id'];
                unset($postData['id']);
                unset($postData['specs']);
                $postData['createtime'] =  date('Y-m-d H:i:s',time());
                $postData['unit_price'] = $unit_price / $formData['num'] * $postData['product_num_l'];
                Db::name('deposit_log')->insert($postData);

                Db::name('deposit')->where('id',$id)->update(['status'=>$status]);

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                return $this->axiosMsg($e->getMessage(),false);
            }

            return $this->axiosMsg('领取成功！', true);
        }
        if(!$formData){
            return $this->error('订单不存在或权限不足');
        }
        $formData['user_name'] = Db::name('user')->where('id', $formData['user_id'])->value('nick');
        $formData['product_name'] = Db::name('product')->where('id', $formData['product_id'])->value('name');
        $this->assign('formData', $formData);
        // halt($formData);
        $warehouses = Db::name('warehouse')->field('id,name')->where('shop_id',session('shop_id'))->select();
        $this->assign('warehouses',$warehouses);
        return $this->fetch();
    }
    public function getProductPrice()
    {
        $pid = $this->request->param('pid');
        $price = Db::name('product')->where('id',$pid)->value('price2');
        return $price;
    }

    public function look()
    {
        $id = $this->request->param('id');
        $list = Db::name('deposit_log')->where('d_id',$id)->select();
        // halt($id);
        $this->assign('lists', $list);
        return $this->fetch();
    }

    public function dayin()
    {
        $id = $this->request->param('id');
        $formData = Db::name('deposit')->where('id', $id)->find();
        $det = Db::name('deposit_log')->where('d_id',$id)->order('id desc')->find();
        $formData['user_name'] = Db::name('user')->where('id',$formData['user_id'])->value('nick');
        $product = Db::name('product')->where('id',$formData['product_id'])->find();
        $unit = '';
        if(Db::name('warehouse')->where('id',$formData['warehouse_id'])->value('type') == 1){
            $unit = Db::name('unit')->where('id',$product['decomposition_id'])->value('name');
        }else{
            $unit = Db::name('unit')->where('id',$product['unit_id'])->value('name');
        }
        $this->assign('unit',$unit);
        $formData['product_specs'] = $product['specs'];
        $formData['shop_name'] = Db::name('shop')->where('id',$formData['shop_id'])->value('name');
        $this->view->engine->layout(false);
        $this->assign('det', $det);
        $this->assign('formData', $formData);
        return $this->fetch('dayin');
        // return $this->fetch();
    }


    public function tuihuo()
    {
        $id = $this->request->param('id');
        $formData = Db::name('deposit')->where('id', $id)->find();
        if($this->request->isPost()){
            $postData = $this->request->post();
            $sn = $formData['sn'];
            if(!isset($postData['account_id']) || empty($postData['account_id'])){
                return $this->axiosMsg('支出账户不能为空！',false);
            }
            // 退产品单
            $postData['createtime'] = time();
            $productArr = $postData['productData'];
            if(empty($postData['productData']) || !isset($postData['productData'])){
                return $this->axiosMsg("产品不能为空", false);
            }

            // 退单表
            $postData['products'] = json_encode($productArr);
            $postData['sn'] = $sn;
            $postData['leixing'] = 2;
            $postData['d_id'] = $id;
            $postData['technician_ids'] = implode(',',$postData['technician_ids']);
            $postData['shop_id'] = session('shop_id');
            unset($postData['productData']);

            try {
                Db::name('aftermarket_product')->insert($postData);
            } catch (\Exception $e) {
                return $this->axiosMsg('退款失败',false);
            }
            return $this->axiosMsg('退款成功！', true);
        }


        $this->assign('user_id',$formData['user_id']);
        $userArr = Db::name('user')->where('id',$formData['user_id'])->field('id,nick')->select();
        $this->assign('userArr',$userArr);
        $account_arr = AccountModel::where('status',1)->field('id,name')->all();
		$account_arr[] = ['id'=> -2,'name'=>'会员卡赠送'];
		$account_arr[] = ['id'=> -3,'name'=>'赠送'];
        $this->assign('accountArr', $account_arr);
		$products = Db::name('product')->where('status',1)->where('id',$formData['product_id'])->field('id,name,price2')->all();
		$this->assign('products', $products);
		$warehouses = Db::name('warehouse')->field('id,name')->select();
		$this->assign('warehouses',$warehouses);
        return $this->fetch();
    }
}
